<template>
  <el-dialog v-model="dialogVisible" title="创建成绩" width="800">
    <div style="margin-bottom: 20px; font-size: 14.5px; font-weight: 500">
      今天还可更换 {{ userInfo.score_update }}次，
      成绩决定推荐结果及录取概率，请认真填写
    </div>

    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      label-width="100px"
      class="demo-ruleForm"
      status-icon
    >
      <el-form-item label="分数" prop="score">
        <el-input
          v-model="ruleForm.score"
          style="width: 200px"
          @input="handleInput(ruleForm.score)"
          maxlength="3"
        />
        <div class="titleHeader">
          <el-icon>
            <InfoFilled />
          </el-icon>
          {{ pointOut }}
        </div>
      </el-form-item>

      <el-form-item label="语数外总分" prop="score_wx" v-if="isDzTypeDiff == 1">
        <el-input
          v-model="ruleForm.score_wx"
          style="width: 200px"
          @input="handleInput_wx(ruleForm.score_wx)"
          maxlength="3"
        ></el-input>
        <div class="titleHeader">
          <el-icon>
            <InfoFilled />
          </el-icon>
          分数区间 100-450
        </div>
      </el-form-item>

      <el-form-item
        :label="data.title"
        v-for="(data, index) in xkdata"
        :key="index"
        :prop="data.type == 1 ? 'radio' : 'checkbox'"
      >
        <el-radio-group v-if="data.type == 1" v-model="ruleForm.radio">
          <el-radio
            :value="value"
            v-for="(value, key) in data.item"
            :key="key"
            >{{ key }}</el-radio
          >
        </el-radio-group>
        <el-checkbox-group
          v-else
          v-model="ruleForm.checkbox"
          :max="data.number * 1"
        >
          <el-checkbox
            :value="value"
            v-for="(value, key) in data.item"
            :key="key"
            >{{ key }}</el-checkbox
          >
        </el-checkbox-group>
      </el-form-item>

      <el-form-item style="display: flex; justify-content: flex-end">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          确定
        </el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>
<script setup>
import { reactive, ref, computed } from 'vue';
import { EditUser } from '@/api/user';
import { useStore } from 'vuex';
import router from '@/router';
import { setToken } from '@/utils/auth';
import jwtDecode from 'jwt-decode';

const store = useStore();
const userInfo = store.getters.user.userInfo; // 用户信息
const dialogVisible = ref(false);
const ruleFormRef = ref(null);
const provinceData = computed(
  () => JSON.parse(localStorage.getItem('provinceList')) || [],
);
const ruleForm = reactive({
  score: '',
  radio: '',
  checkbox: [],
  score_wx: '',
});

const rules = reactive({
  score: [
    {
      required: true,
      message: '请输入分数',
      trigger: 'blur',
    },
    {
      validator: (rule, value, callback) => {
        if (example.value == 46) {
          if (value < 100 || value > 900) {
            callback(new Error('分数区间 100-900'));
          } else {
            callback();
          }
        } else if (example.value == 31) {
          if (value < 100 || value > 660) {
            callback(new Error('分数区间 100-660'));
          } else {
            callback();
          }
        } else {
          if (value < 100 || value > 750) {
            callback(new Error('分数区间 100-750'));
          } else {
            callback();
          }
        }
      },
      trigger: 'blur',
    },
  ],
  score_wx: [
    {
      message: '请输入语数外总分',
      trigger: 'blur',
    },
    {
      validator: (rule, value, callback) => {
        if (value < 100 || value > 450) {
          callback(new Error('分数区间 100-450'));
        } else {
          callback();
        }
      },
      trigger: 'blur',
    },
  ],
  radio: [
    {
      required: true,
      message: '请选择科类',
      trigger: 'change',
    },
  ],
  checkbox: [
    {
      required: true,
      message: '请选择科目',
      trigger: 'change',
    },
  ],
});

// 父级传递的学生数据
const xkdata = ref({}); // 选科科类信息

// 只允许输入数字
const handleInput = (score) => {
  ruleForm.score = score.replace(/[^\d]/g, '');
};
const handleInput_wx = (score) => {
  ruleForm.score_wx = score.replace(/[^\d]/g, '');
};

// 判断省份
const example = ref(null); //判断个别省份总分
const pointOut = ref('分数区间 100-750');
const isDzTypeDiff = ref(''); //判断北京、天津 1 显示， 0 不显示
const getisDzTypeDiff = () => {
  if (store.getters.user.userInfo.pid == '46') {
    example.value = 46;
    pointOut.value = '分数区间 100-900';
  } else if (store.getters.user.userInfo.pid == '31') {
    example.value = 31;
    pointOut.value = '分数区间 100-660';
  }
  if (store.getters.user.userInfo?.pid && provinceData.value.length > 0) {
    isDzTypeDiff.value = provinceData.value.filter(
      (i) => i.id == store.getters.user.userInfo.pid,
    )[0].isDzTypeDiff;
  } else {
    isDzTypeDiff.value = 0;
  }
};
getisDzTypeDiff();

function submitForm(formEl) {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      let xkInfos = {};
      xkdata.value.forEach((item) => {
        xkInfos = {
          ...xkInfos,
          ...item.item,
        };
      });

      if (ruleForm.radio.length > 0) {
        ruleForm.checkbox.push(ruleForm.radio);
      }

      let xkIds = [];
      ruleForm.checkbox.forEach((item) => {
        xkIds.push(item);
      });
      xkIds = [...new Set(xkIds)];

      let data = {};
      data['score'] = ruleForm.score;
      data['sgid'] = xkIds.toString();
      data['score_wx'] = ruleForm.score_wx;
      EditUser(data).then((res) => {
        dialogVisible.value = false;

        let userInfo = jwtDecode(res.token);
        store.dispatch('user/changeToken', res.token);
        store.dispatch('user/changeUserInfo', userInfo.data); //将用户信息存储到vuex中
        setToken(res.token);

        router
          .replace({
            path: '/batchInfo',
          })
          .then(() => {
            window.location.reload();
          });
      });
    }
  });
}

function openChange() {
  dialogVisible.value = true;
  ruleForm.score = '';
  ruleForm.radio = '';
  ruleForm.checkbox = [];

  if (userInfo.xk_type == 1) {
    xkdata.value = [
      {
        type: '1', // 1-单选，2-多选
        title: '选考科目',
        item: {
          文科: '22',
          理科: '11',
        },
      },
    ];
  } else if (userInfo.xk_type == 2) {
    xkdata.value = [
      {
        type: '2',
        number: '3',
        title: '选考科目',
        item: {
          物理: '1',
          化学: '2',
          生物: '3',
          政治: '6',
          历史: '4',
          地理: '5',
        },
      },
    ];
  } else {
    xkdata.value = [
      {
        // 单选
        type: '1',
        title: '首选科目',
        item: {
          物理: '1',
          历史: '4',
        },
      },
      {
        // 双选
        type: '2',
        number: '2',
        title: '再选科目',
        item: {
          化学: '2',
          生物: '3',
          政治: '6',
          地理: '5',
        },
      },
    ];
  }

  if (userInfo.pid == '33') {
    // 省ID=33 浙江7选3
    xkdata.value[0]['item']['技术'] = '7';
  }
}

// 暴露方法
defineExpose({
  openChange,
});
</script>
<style lang="scss" scoped>
.titleHeader {
  display: flex;
  align-items: center;
  background-color: #f4f4f5;
  color: #909399;
  margin-left: 20px;
  padding: 0 8px;
}
</style>
